#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

char* addBinary(const char* a,const char* b)
{
    int length1 = strlen(a);
    int length2 = strlen(b);
    int longstr = (length1 > length2) ? length1 : length2;
    char* ret = (char*)malloc((longstr + 2) * sizeof(char));
    memset(ret, 0, longstr + 2);
    int pos1 = length1 - 1;
    int pos2 = length2 - 1;
    int pos = 0;
    unsigned char add = '0';
    unsigned char num = 0;

    while (pos1 >= 0 && pos2 >= 0)
    {
        num = a[pos1] + b[pos2] + add;
        if (3 * '0' == num)
        {
            ret[pos++] = '0';
        }
        else if (2 * '0' + '1' == num)
        {
            ret[pos++] = '1';
            add = '0';
        }
        else if (2 * '1' + '0' == num)
        {
            ret[pos++] = '0';
            add = '1';
        }
        else if (3 * '1' == num)
        {
            ret[pos++] = '1';
        }
        --pos1;
        --pos2;
    }
    while (pos1>=0)
    {
        num = a[pos1] + add;
        if ('1' + '0' == num)
        {
            ret[pos++] = '1';
            add = '0';
        }
        else if (2 * '1' == num)
        {
            ret[pos++] = '0';
        }
        else if (2 * '0' == num)
        {
            ret[pos++] = '0';
        }
        --pos1;
    }
    while (pos2>=0)
    {
        num = a[pos2] + add;
        if ('1' + '0' == num)
        {
            ret[pos++] = '1';
            if ('1' == add)
            {
                add = '0';
            }
        }
        else if (2 * '1' == num)
        {
            ret[pos++] = '0';
        }
        else if (2 * '0' == num)
        {
            ret[pos++] = '0';
        }
        --pos2;
    }
    if ('1' == add)
    {
        ret[pos++] = '1';
    }
    int left = 0;
    int right = pos - 1;
    while (left < right)
    {
        char temp = ret[left];
        ret[left] = ret[right];
        ret[right] = temp;
        ++left;
        --right;
    }

    return ret;
}

int main()
{
    const char* a = "1";
    const char* b = "111";
    char* ret = addBinary(a, b);

    return 0;

}